using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using Honest.MES.Contracts.Attributes;
using Honest.MES.Contracts.Interfaces;
using Honest.MES.WPF.Constants;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation.Regions;

namespace Honest.MES.WPF.ViewModels
{
    /// <summary>
    /// 菜单视图模型
    /// </summary>
    public class MenuViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IModuleDiscoveryService _moduleDiscoveryService;
        private readonly ILoggerService _loggerService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="regionManager">区域管理器</param>
        /// <param name="moduleDiscoveryService">模块发现服务</param>
        /// <param name="loggerService">日志服务</param>
        public MenuViewModel(
            IRegionManager regionManager,
            IModuleDiscoveryService moduleDiscoveryService,
            ILoggerService loggerService)
        {
            _regionManager = regionManager;
            _moduleDiscoveryService = moduleDiscoveryService;
            _loggerService = loggerService;

            // 初始化命令
            NavigateCommand = new DelegateCommand<string>(OnNavigate);
            ExitCommand = new DelegateCommand(OnExit);

            // 加载模块信息
            LoadModules();
        }

        /// <summary>
        /// 导航命令
        /// </summary>
        public ICommand NavigateCommand { get; }
        
        /// <summary>
        /// 退出命令
        /// </summary>
        public ICommand ExitCommand { get; }

        private ObservableCollection<ModuleMenuItem> _menuItems = new ObservableCollection<ModuleMenuItem>();
        
        /// <summary>
        /// 菜单项集合
        /// </summary>
        public ObservableCollection<ModuleMenuItem> MenuItems
        {
            get => _menuItems;
            set => SetProperty(ref _menuItems, value);
        }

        /// <summary>
        /// 加载模块信息并构建菜单
        /// </summary>
        private void LoadModules()
        {
            MenuItems.Clear();

            try
            {
                if (_moduleDiscoveryService == null) return;
                
                var moduleTypes = _moduleDiscoveryService.DiscoverModules();
                if (moduleTypes == null || !moduleTypes.Any()) return;

                // 按GroupName分组模块
                var groupedModules = moduleTypes
                    .Select(type => new
                    {
                        Type = type,
                        Attribute = type?.GetCustomAttribute<ModelInfoAttribute>()
                    })
                    .Where(x => x != null && x.Attribute != null)
                    .GroupBy(x => x.Attribute.GroupName)
                    .OrderBy(g => g.Key);

                // 处理每个模块组
                foreach (var group in groupedModules)
                {
                    if (group == null || string.IsNullOrEmpty(group.Key)) continue;

                    var groupItems = group.ToList();
                    
                    // 检查是否为单模块组
                      try
                      {
                          if (IsSingleModuleGroup(groupItems) && groupItems != null && groupItems.Count > 0)
                          {
                              var singleModule = groupItems[0];
                              if (singleModule != null)
                              {
                                  AddSingleModuleGroupMenuItem(group, singleModule);
                              }
                              continue;
                          }
                      }
                      catch
                      {
                          // 忽略异常，继续处理下一个组
                      }

                    // 添加普通模块组菜单项
                    AddModuleGroupMenuItems(group, groupItems);
                }
            }
            catch (Exception ex)
            {
                _loggerService?.Error(ex, "加载模块信息失败");
            }
        }

        /// <summary>
        /// 检查是否为单模块组
        /// </summary>
        /// <param name="groupItems">组内模块</param>
        /// <returns>是否为单模块组</returns>
        private bool IsSingleModuleGroup(dynamic groupItems)
        {
            if (groupItems == null) return false;
            
            try
            {
                if (groupItems?.Count != 1) return false;
                
                var singleModule = groupItems[0];
                if (singleModule == null || singleModule.Attribute == null) return false;
                
                var modelKey = singleModule.Attribute.ModelKey ?? string.Empty;
                var groupKey = singleModule.Attribute.GroupKey ?? string.Empty;
                return !string.IsNullOrEmpty(modelKey) &&
                       !string.IsNullOrEmpty(groupKey) &&
                       modelKey == groupKey;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 添加单模块组菜单项
        /// </summary>
        private void AddSingleModuleGroupMenuItem(IGrouping<string, dynamic> group, dynamic singleModule)
        {
            if (group == null || singleModule == null) return;
            
            string viewName = string.Empty;
            string groupName = string.Empty;
            
            try
            {
                if (singleModule.Attribute != null)
                {
                    // 安全获取viewName
                    var viewNameObj = singleModule.Attribute?.ViewName;
                    if (viewNameObj != null)
                    {
                        viewName = viewNameObj.ToString();
                    }
                    
                    // 安全获取groupName
                    var groupNameObj = singleModule.Attribute.GroupName;
                    if (groupNameObj != null)
                    {
                        groupName = groupNameObj.ToString();
                    }
                }
            }
            catch { }
            
            var menuItem = new ModuleMenuItem
            {
                Title = group?.Key ?? string.Empty,
                NavigationPath = viewName,
                FullViewName = viewName,
                GroupName = groupName,
                IsCategory = false,
                IsSingleModuleGroup = true
            };
            MenuItems.Add(menuItem);
        }

        /// <summary>
        /// 添加普通模块组菜单项
        /// </summary>
        private void AddModuleGroupMenuItems(IGrouping<string, dynamic> group, dynamic groupItems)
        {
            if (group == null || groupItems == null) return;
            
            // 添加组标题菜单项
            var groupMenuItem = new ModuleMenuItem
            {
                Title = group?.Key ?? string.Empty,
                IsCategory = true,
                GroupName = group?.Key ?? string.Empty
            };
            MenuItems.Add(groupMenuItem);

            // 添加组内子菜单项
            var moduleList = groupItems as IEnumerable<object>;
            if (moduleList == null) return;
            
            var safeModuleList = moduleList.ToList();
            if (safeModuleList == null || !safeModuleList.Any()) return;
            
            foreach (var moduleObj in safeModuleList)
            {
                if (moduleObj == null) continue;
                
                var module = moduleObj as object;
                if (module == null) continue;
                
                string modelName = string.Empty;
                string viewName = string.Empty;
                string groupName = string.Empty;
                
                try
                {
                    // 使用反射安全地访问属性
                    var attribute = GetPropertyValue(module, "Attribute");
                    if (attribute != null)
                    {
                        modelName = GetStringPropertyValue(attribute, "ModelName");
                        viewName = GetStringPropertyValue(attribute, "ViewName");
                        groupName = GetStringPropertyValue(attribute, "GroupName");
                    }
                }
                catch { }
                
                if (string.IsNullOrEmpty(modelName)) continue;
                
                var subMenuItem = new ModuleMenuItem
                {
                    Title = modelName ?? string.Empty,
                    NavigationPath = viewName,
                    FullViewName = viewName,
                    GroupName = groupName
                };
                MenuItems.Add(subMenuItem);
            }
            
            // 对子菜单项按标题排序
            MenuItems = new ObservableCollection<ModuleMenuItem>(MenuItems.OrderBy(item => item.Title));
        }

        /// <summary>
        /// 导航命令执行方法
        /// </summary>
        /// <param name="navigationPath">导航路径</param>
        private void OnNavigate(string navigationPath)
        {
            if (_regionManager == null) return;
            
            // 添加详细日志记录
            if (_loggerService != null)
            {
                _loggerService.Info(string.Format("导航命令触发，导航路径: {0}", navigationPath ?? "空"));
                // 尝试找到对应的菜单项以获取更多信息
                if (MenuItems != null)
                {
                    var menuItem = MenuItems.FirstOrDefault(item => item?.NavigationPath == navigationPath);
                    if (menuItem != null)
                    {
                        _loggerService.Info(string.Format("菜单项信息 - 标题: {0}, 组名: {1}, 完整视图名: {2}", 
                            menuItem.Title ?? "空", 
                            menuItem.GroupName ?? "空", 
                            menuItem.FullViewName ?? "空"));
                    }
                }
            }
            
            if (!string.IsNullOrEmpty(navigationPath))
            {
                try
                {
                    // 使用完整视图名称进行导航
                    _loggerService?.Info(string.Format("尝试导航到: {0}", navigationPath));
                    _regionManager.RequestNavigate(RegionNames.MainRegion, navigationPath);
                }
                catch (Exception ex)
                {
                    _loggerService?.Error(ex, string.Format("导航失败: {0}", ex.Message));
                }
            }
        }

        /// <summary>
        /// 退出命令执行方法
        /// </summary>
        private void OnExit()
        {
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 从完整视图类型名称中提取简单视图名称
        /// </summary>
        /// <param name="fullViewName">完整的视图类型名称</param>
        /// <returns>简单视图名称</returns>
        private string ExtractViewName(string fullViewName)
        {
            if (string.IsNullOrEmpty(fullViewName))
                return string.Empty;

            // 提取类型名称的最后一部分
            int lastDotIndex = fullViewName.LastIndexOf('.');
            if (lastDotIndex >= 0 && lastDotIndex < fullViewName.Length - 1)
            {
                return fullViewName.Substring(lastDotIndex + 1);
            }

            return fullViewName;
        }

        /// <summary>
        /// 安全地从对象获取属性值
        /// </summary>
        private object GetPropertyValue(object obj, string propertyName)
        {
            if (obj == null || string.IsNullOrEmpty(propertyName)) return null;

            try
            {
                var type = obj.GetType();
                if (type == null) return null;

                var property = type.GetProperty(propertyName);
                if (property != null && property.CanRead)
                {
                    return property.GetValue(obj);
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 安全地从对象获取字符串属性值
        /// </summary>
        private string GetStringPropertyValue(object obj, string propertyName)
        {
            try
            {
                var value = GetPropertyValue(obj, propertyName);
                if (value == null)
                    return string.Empty;

                return value.ToString() ?? string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }
    }

    /// <summary>
    /// 菜单项数据模型
    /// </summary>
    public class ModuleMenuItem
    {
        /// <summary>
        /// 菜单项标题
        /// </summary>
        public string Title { get; set; }
        
        /// <summary>
        /// 导航路径
        /// </summary>
        public string NavigationPath { get; set; }
        
        /// <summary>
        /// 完整视图名称
        /// </summary>
        public string FullViewName { get; set; }
        
        /// <summary>
        /// 所属分组名称
        /// </summary>
        public string GroupName { get; set; }
        
        /// <summary>
        /// 是否为分类项
        /// </summary>
        public bool IsCategory { get; set; }
        
        /// <summary>
        /// 是否为单模块组菜单项
        /// </summary>
        public bool IsSingleModuleGroup { get; set; } = false;
    }
}